package com.ruoyi.project.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.http.HttpsUtil;
import com.ruoyi.project.wx.controller.util.WxJsSdkSignUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WxController {
	@Value("${wx.appid}")
	private  String appId;
	@Value("${wx.secret}")
	private String secret;

	/**
	 * 
	 * @return
	 * @throws Exception 
	 */	
	@RequestMapping("/jsApi")
	@ResponseBody
	public Object getTextBook(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
		// ################# ------------jsapi 授权 start --------------###############
		//前置条件，session中没有存储
		long nowMillis=Calendar.getInstance().getTimeInMillis()/1000;
		boolean isRefreshTicket=true;
		String jsapi_ticket=StringUtils.convertNull(request.getSession().getAttribute("jsapi_ticket_token"));
		if(!jsapi_ticket.equals("")){
			//判断session内数据是否超7200秒，考虑到网络延迟，这里按7100判断
			Object obj_ticket_millis=request.getSession().getAttribute("jsapi_ticket_millis");
			if(obj_ticket_millis!=null){
	 			long session_millis=(long)obj_ticket_millis;
	 			if(nowMillis-session_millis<=7100){
	 				isRefreshTicket=false;
	 			}
			}else{
				isRefreshTicket=true;
			}
		}
		

		if(isRefreshTicket){
			//1. 获取access_token（有效期7200秒，开发者必须在自己的服务全局缓存access_token）
			String url_get_token="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
			String str= HttpUtils.sendGet(url_get_token,"");
			JSONObject jb=JSONObject.parseObject(str);
			String accessToken=StringUtils.convertNull(jb.get("access_token"));
			request.getSession().setAttribute("jsapi_access_token_millis", nowMillis);
			request.getSession().setAttribute("jsapi_access_token",accessToken);
			jb.clear();
			//2.采用http GET方式请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）：
			String url_get_jsapi="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
			String str2= HttpsUtil.sendDataByGet(url_get_jsapi);
			jb=JSONObject.parseObject(str2);
			
			if(StringUtils.convertNull(jb.get("errcode")).equals("0")) {
				nowMillis=Calendar.getInstance().getTimeInMillis()/1000;
				jsapi_ticket=StringUtils.convertNull(jb.get("ticket"));
				request.getSession().setAttribute("jsapi_ticket_millis", nowMillis);
				request.getSession().setAttribute("jsapi_ticket_token",jsapi_ticket);
			}
		}

		//3.签名
//		String noncestr=ChunQiuTool.getNonceStr();
//		String timestamp=System.currentTimeMillis()+"";
//		timestamp=timestamp.length()>10?timestamp.substring(0,10):timestamp;
//		//String url="http://www.beidanci.online/bdc-wx/textbook/detail?id=26&type=3";
//		String string1="jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
//		//string1="jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value";
//		String signature= SHA1.encode(string1);
		//################# ------------jsapi 授权 end --------------###############
		
		
		//3.签名(用签名工具类)
		 // 注意 URL 一定要动态获取，不能 hardcode
        Map<String, String> ret = WxJsSdkSignUtil.sign(jsapi_ticket, url);
        ret.put("appid", appId);
        ret.put("ticket",jsapi_ticket);
//        for (Map.Entry entry : ret.entrySet()) {
//            System.out.println(entry.getKey() + ", " + entry.getValue());            
//        }
		
//        ret.put("my_timestamp",timestamp);
//        ret.put("my_nonceStr",noncestr);
//        ret.put("my_signature",signature);
        
//        jsapi_ticket=jsapi_ticket&noncestr=d682082b-5462-45cb-b86d-b9b94b98cddb&timestamp=1583994008&url=http://example.com
//        	timestamp, 1583994008
//        	nonceStr, d682082b-5462-45cb-b86d-b9b94b98cddb
//        	jsapi_ticket, jsapi_ticket
//        	signature, f21224356d690cdefba25870e5e0ad86cdb72d90
//        	url, http://example.com
        
		return ret;
	}
	
}
